/*
 * IIC_UNIT.c
 *
 *  Created on: Nov 5, 2021
 *      Author: ITry
 */

#include "IIC_UNIT.h"
#include "SoftIIC.h"

/*
 * SDA:PC7
 * SCL:PC8
 */
int iic_read_byte (void* bus_param, uint8_t dev_addr, uint8_t reg_addr, uint8_t *data){
	return iic_read_bytes(bus_param, dev_addr, reg_addr, 1, data);
}

int iic_read_bytes (void* bus_param, uint8_t dev_addr, uint8_t reg_addr, uint8_t len, uint8_t *data){
	uint8_t err = 0;
	uint8_t i = 0;
	iic_start();
	do {
		if (iic_send_check(dev_addr | IIC_WRITE)) {
			err = 2;
			break;
		}
		if (iic_send_check(reg_addr)) {
			err = 3;
			break;
		}
		iic_start();
		if (iic_send_check(dev_addr | IIC_READ)) {
			err = 4;
			break;
		}
		for (i = 0; i < len; i++) {
			data[i] = iic_readbyte();
			if (i != len - 1) {
				iic_ack(); /* 读完非最后一个字节后， 产生应答信号 */
			} else {
				iic_nack(); /* 最后一个字节读完后 产生非应答信号,以提示Slave设备准备接收Stop信号 */
			}
		}
		err = 0;
	} while (0);
	iic_stop();
	return err;
}

int iic_write_byte (void* bus_param, uint8_t dev_addr, uint8_t reg_addr, uint8_t data){

	uint8_t err = 0;
	iic_start();
	do {
		if (iic_send_check(dev_addr | IIC_WRITE)) {
			err = 2;
			break;
		}
		if (iic_send_check(reg_addr)) {
			err = 3;
			break;
		}
		err = 0;
		if (iic_send_check(data)) {
			err = 4;
			break;
		}
	} while (0);
	iic_stop();
	return err;
}
